package com.aigc.sclassroom.interceptors;

import com.aigc.sclassroom.utils.JwtUtil;
import com.aigc.sclassroom.utils.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authHeader = request.getHeader("Authorization");
        logger.info("Received Authorization header: {}", authHeader);
        if (authHeader == null) {
            logger.info("Authorization header is missing");
            response.setStatus(401);
            return false;
        }
        try {
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(authHeader);
            logger.info("Token from Redis: {}", redisToken);
            if (redisToken == null) {
                logger.info("Token is invalid: {}", authHeader);
                throw new RuntimeException();
            }
            Map<String, Object> claims = JwtUtil.parseToken(authHeader);
            ThreadLocalUtil.set(claims);
            return true;
        } catch (Exception e) {
            logger.error("Token verification failed: {}", e.getMessage());
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}